/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package application;

import controleur.ConnexionBD;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 *
 * @author James
 */
public class CritiqueDAO {

    private static PreparedStatement pstmt;
    private static ResultSet results;

    public static ResultSet getCoteMoyenne(final String isbn) {
        final String query = "select AVG(cote) cote_moyenne from critique where isbn=?";

        try {
            pstmt = ConnexionBD.creerConnexion().prepareStatement(query);
            pstmt.setString(1, isbn);
            results = pstmt.executeQuery();

        } catch (Exception e) {
            return null;
        }
        return results;
    }

    public static ResultSet getCritiquesLivre(final String isbn) {
        final String query = "select * from critique where isbn=? order by id_critique desc";

        try {
            pstmt = ConnexionBD.creerConnexion().prepareStatement(query);
            pstmt.setString(1, isbn);
            results = pstmt.executeQuery();

        } catch (Exception e) {
            return null;
        }
        return results;
    }

    public static ResultSet getCritiqueMembre(final String isbn, final String idMembre) {
        final String query = "select * from critique where isbn=? and id_membre=?";

        try {
            pstmt = ConnexionBD.creerConnexion().prepareStatement(query);
            pstmt.setString(1, isbn);
            pstmt.setString(2, idMembre);
            results = pstmt.executeQuery();

        } catch (Exception e) {
            return null;
        }
        return results;
    }

    public static int ecrireCritique(final CritiqueBean c) {
        final String query = "INSERT INTO critique (isbn, id_membre, critique, cote) VALUES (?, ?, ?, ?)";

        int rowResults;

        try {
            pstmt = ConnexionBD.creerConnexion().prepareStatement(query);
            pstmt.setString(1, c.getIsbn());
            pstmt.setInt(2, Integer.parseInt(c.getIdMembre()));
            pstmt.setString(3, c.getCritique());
            pstmt.setString(4, c.getCote());
            rowResults = pstmt.executeUpdate();
        } catch (Exception e) {
            rowResults = 0;
        }
        return rowResults;
    }
    
    public static int supprimerCritique(final String idCritique) {
        final String query = "DELETE FROM critique WHERE id_critique=?";
        
        int rowResults;
        
        try {
            pstmt = ConnexionBD.creerConnexion().prepareStatement(query);
            pstmt.setInt(1, Integer.parseInt(idCritique));
            rowResults = pstmt.executeUpdate();
        } catch (Exception e) {
            rowResults = 0;
        }
        return rowResults;
    }
}
